const puppeteer = require('puppeteer');

const fs = require('fs')
const https = require('https');
let isStart=false;
const getUrl = async (item) => {

   const browser = await puppeteer.launch({
      headless: true, // 有界面模式
      devtools: true, // 自动打开devtool
      defaultViewport: {
         width: 1500,
         height: 800
      }
   }); //启动浏览器实例
   const page = await browser.newPage(); //创建一个新页面
   // await page.emulate(puppeteer.devices[`iPhone ${Math.floor(Math.random()*8)}`]); //模拟iphone6打开页面
   await page.evaluateOnNewDocument(() => {
      Object.defineProperty(navigator, 'webdriver', {
         get: () => false,
      });
   });
   page.setUserAgent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36")

   await page.evaluateOnNewDocument(() => {
      Object.defineProperty(navigator, 'plugins', {
         get: () => [{
               0: {
                  type: "application/x-google-chrome-pdf",
                  suffixes: "pdf",
                  description: "Portable Document Format",
                  enabledPlugin: Plugin
               },
               description: "Portable Document Format",
               filename: "internal-pdf-viewer",
               length: 1,
               name: "Chrome PDF Plugin"
            },
            {
               0: {
                  type: "application/pdf",
                  suffixes: "pdf",
                  description: "",
                  enabledPlugin: Plugin
               },
               description: "",
               filename: "mhjfbmdgcfjbbpaeojofohoefgiehjai",
               length: 1,
               name: "Chrome PDF Viewer"
            },
            {
               0: {
                  type: "application/x-nacl",
                  suffixes: "",
                  description: "Native Client Executable",
                  enabledPlugin: Plugin
               },
               1: {
                  type: "application/x-pnacl",
                  suffixes: "",
                  description: "Portable Native Client Executable",
                  enabledPlugin: Plugin
               },
               description: "",
               filename: "internal-nacl-plugin",
               length: 2,
               name: "Native Client"
            }
         ],
      });
   });

   await page.goto(item.url); //进入指定网页
   if(!isStart)console.log('-----开始解析-------')
   isStart=true;
   // fs.writeFile('1.html', content, function (err) {
   //    if (err) {
   //       return console.error(err);
   //    }
   //    console.log("数据写入成功！");
   //    console.log("--------我是分割线-------------")

   // });
   let src = await page.$eval('.xg-video-container video', e => e.src) || await page.$eval('.xg-video-container video source', e => e.src)
   let title = await page.$eval('.mzZanXbP span span span span', e => e.innerText)
   await browser.close();
   return {
      src,
      title
   };
}
const downloadVideo =async item => {
   // 判断视频文件是否已经下载
   await getVideoData(item.src, 'binary').then( fileData => {
       savefileToPath(item.title, fileData).then(res=>{
          console.log(res)
       })
   })
}

function getVideoData(url, encoding) {
   return new Promise((resolve, reject) => {
      let req = https.get(url, function (res) {
         let result = ''
         encoding && res.setEncoding(encoding)
         res.on('data', function (d) {
            result += d
         })
         res.on('end', function () {
            resolve(result)
         })
         res.on('error', function (e) {
            reject(e)
         })
      })
      req.end()
   })
}

function savefileToPath(fileName, fileData) {
   let fileFullName = `./video/${fileName}.mp4`
   return new Promise((resolve, reject) => {
      fs.writeFile(fileFullName, fileData, 'binary', function (err) {
         if (err) {
            console.log('下载失败 error:', err)
         }
         resolve(`已下载完成: ${fileName}`)
      })
   })
}

// 读取id下载视频
let links = fs.readFileSync('./link.txt');
links=links.toString().split('\n')
for (let i = 0; i < links.length; i++) {
   getUrl({
      url: `https://www.douyin.com/video/${links[i]}`
   }).then(res => {
      downloadVideo(res)
   });
}